<template>
  <div class="activity-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>活动管理</span>
          <div class="header-actions">
            <el-input
              v-model="searchText"
              placeholder="搜索活动名称"
              style="width: 200px; margin-right: 10px;"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button @click="handleSearch">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
            <el-button type="primary" @click="handleCreate">
              <el-icon><Plus /></el-icon>
              新建活动
            </el-button>
            <el-button @click="handleRefresh">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="activityList" v-loading="loading" stripe>
        <el-table-column label="活动名称" width="200" show-overflow-tooltip>
          <template #default="scope">
            <div>
              <div style="font-weight: 600;" class="event-name">{{ scope.row.title }}</div>
              <div style="font-size: 12px; color: #909399; margin-top: 2px;" class="event-title">
                {{ scope.row.eventTitle || '无主题' }}
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="location" label="地点" width="180" show-overflow-tooltip />
        
        <el-table-column prop="recommended" label="推荐" width="80" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.recommended === 1 ? 'success' : 'info'">
              {{ scope.row.recommended === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="price" label="报名费" width="100" align="center">
          <template #default="scope">
            <span style="color: #f56c6c; font-weight: 600;">
              ¥{{ scope.row.price || 0 }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column prop="participantCount" label="报名人数" width="100" align="center">
          <template #default="scope">
            <el-tag type="info">{{ scope.row.participantCount || 0 }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="maxParticipants" label="限制人数" width="100" align="center" />
        
        <el-table-column prop="startTime" label="开始时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.startTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="endTime" label="结束时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.endTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="250" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleViewRegistrations(scope.row)">
              报名数据
            </el-button>
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-dropdown @command="(command) => handleCommand(command, scope.row)">
              <el-button size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="changeStatus">
                    {{ scope.row.status === 'active' ? '暂停' : '启用' }}
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
    
    <!-- 活动表单对话框 -->
    <el-dialog
      v-model="formDialogVisible"
      :title="isEdit ? '编辑活动' : '新建活动'"
      width="800px"
      :before-close="handleCloseForm"
    >
      <el-form
        ref="activityFormRef"
        :model="activityForm"
        :rules="activityRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="活动名称" prop="title">
              <el-input v-model="activityForm.title" placeholder="请输入活动名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动主题" prop="eventTitle">
              <el-input v-model="activityForm.eventTitle" placeholder="请输入活动主题" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="活动类型" prop="type">
              <el-select v-model="activityForm.type" placeholder="请选择活动类型">
                <el-option label="文化活动" value="culture" />
                <el-option label="体育活动" value="sports" />
                <el-option label="学术讲座" value="lecture" />
                <el-option label="社交活动" value="social" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="推荐活动" prop="recommended">
              <el-switch
                v-model="activityForm.recommended"
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="活动描述" prop="description">
          <el-input
            v-model="activityForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入活动描述"
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="activityForm.startTime"
                type="datetime"
                placeholder="选择开始时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                v-model="activityForm.endTime"
                type="datetime"
                placeholder="选择结束时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="活动地点" prop="location">
              <el-input v-model="activityForm.location" placeholder="请输入活动地点" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="限制人数" prop="maxParticipants">
              <el-input-number
                v-model="activityForm.maxParticipants"
                :min="1"
                :max="10000"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报名费" prop="price">
              <el-input-number
                v-model="activityForm.price"
                :min="0"
                :precision="2"
                :step="1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="封面图片" prop="coverImage">
          <el-input v-model="activityForm.coverImage" placeholder="请输入图片URL" />
        </el-form-item>
        
        <el-form-item label="活动状态" prop="status">
          <el-radio-group v-model="activityForm.status">
            <el-radio label="pending">未开始</el-radio>
            <el-radio label="active">进行中</el-radio>
            <el-radio label="ended">已结束</el-radio>
            <el-radio label="cancelled">已取消</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="formDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 报名数据对话框 -->
    <el-dialog
      v-model="registrationDialogVisible"
      title="报名数据"
      width="800px"
    >
      <el-table :data="registrationList" v-loading="registrationLoading">
        <el-table-column prop="userInfo.avatarUrl" label="头像" width="80" align="center">
          <template #default="scope">
            <el-avatar :src="scope.row.userInfo.avatarUrl" size="small">
              <el-icon><User /></el-icon>
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="userInfo.nickName" label="用户昵称" />
        <el-table-column prop="registrationTime" label="报名时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.registrationTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'registered' ? 'success' : 'danger'">
              {{ scope.row.status === 'registered' ? '已报名' : '已取消' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="registrationDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="exportRegistrations">导出数据</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Plus, 
  Refresh, 
  Picture, 
  User, 
  ArrowDown 
} from '@element-plus/icons-vue'
import CloudBaseAPI from '@/api/cloudbase'

const activityList = ref([])
const loading = ref(false)
const searchText = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

const formDialogVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const activityFormRef = ref()

const registrationDialogVisible = ref(false)
const registrationList = ref([])
const registrationLoading = ref(false)
const selectedActivity = ref(null)

const activityForm = reactive({
  title: '', // 对应eventName
  eventTitle: '', // 活动主题
  type: '',
  description: '',
  startTime: '',
  endTime: '',
  location: '',
  maxParticipants: 100,
  price: 0, // 报名费
  recommended: 0, // 推荐状态：1=是，0=否
  coverImage: '', // 对应bannerImage
  status: 'pending'
})

const activityRules = {
  title: [
    { required: true, message: '请输入活动名称', trigger: 'blur' }
  ],
  eventTitle: [
    { required: false, message: '请输入活动主题', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择活动类型', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入活动描述', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请输入活动地点', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入报名费', trigger: 'blur' },
    { type: 'number', min: 0, message: '报名费不能为负数', trigger: 'blur' }
  ]
}

// 获取活动列表
const getActivityList = async () => {
  loading.value = true
  try {
    const result = await CloudBaseAPI.getActivityList(
      currentPage.value, 
      pageSize.value, 
      searchText.value
    )
    
    if (result.success) {
      activityList.value = result.data
      total.value = result.total
    } else {
      ElMessage.error(result.message || '获取活动列表失败')
    }
  } catch (error) {
    ElMessage.error('获取活动列表失败')
    console.error('获取活动列表错误:', error)
  } finally {
    loading.value = false
  }
}

// 搜索活动
const handleSearch = () => {
  currentPage.value = 1
  getActivityList()
}

// 刷新列表
const handleRefresh = () => {
  searchText.value = ''
  currentPage.value = 1
  getActivityList()
}

// 页码改变
const handlePageChange = () => {
  getActivityList()
}

// 页面大小改变
const handleSizeChange = () => {
  currentPage.value = 1
  getActivityList()
}

// 新建活动
const handleCreate = () => {
  isEdit.value = false
  resetForm()
  formDialogVisible.value = true
}

// 编辑活动
const handleEdit = (activity) => {
  isEdit.value = true
  Object.assign(activityForm, {
    title: activity.title,
    eventTitle: activity.eventTitle || '',
    type: activity.type,
    description: activity.description,
    startTime: new Date(activity.startTime),
    endTime: new Date(activity.endTime),
    location: activity.location,
    maxParticipants: activity.maxParticipants,
    price: activity.price || 0,
    recommended: activity.recommended || 0,
    coverImage: activity.coverImage,
    status: activity.status === '报名中' ? 'pending' :
            activity.status === '进行中' ? 'active' :
            activity.status === '已结束' ? 'ended' : 'cancelled'
  })
  selectedActivity.value = activity
  formDialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  Object.assign(activityForm, {
    title: '',
    eventTitle: '',
    type: '',
    description: '',
    startTime: '',
    endTime: '',
    location: '',
    maxParticipants: 100,
    price: 0,
    recommended: 0,
    coverImage: '',
    status: 'pending'
  })
  selectedActivity.value = null
}

// 提交表单
const handleSubmit = async () => {
  if (!activityFormRef.value) return
  
  await activityFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      
      try {
        const formData = {
          ...activityForm,
          startTime: activityForm.startTime.toISOString(),
          endTime: activityForm.endTime.toISOString()
        }
        
        let result
        if (isEdit.value) {
          result = await CloudBaseAPI.updateActivity(selectedActivity.value._id, formData)
        } else {
          result = await CloudBaseAPI.createActivity(formData)
        }
        
        if (result.success) {
          ElMessage.success(isEdit.value ? '活动更新成功' : '活动创建成功')
          formDialogVisible.value = false
          getActivityList()
        } else {
          ElMessage.error(result.message || '操作失败')
        }
      } catch (error) {
        ElMessage.error('操作失败')
        console.error('提交活动表单错误:', error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 关闭表单对话框
const handleCloseForm = () => {
  formDialogVisible.value = false
  resetForm()
}

// 查看报名数据
const handleViewRegistrations = async (activity) => {
  selectedActivity.value = activity
  registrationDialogVisible.value = true
  registrationLoading.value = true
  
  try {
    const result = await CloudBaseAPI.getActivityRegistrations(activity._id)
    if (result.success) {
      registrationList.value = result.data
    } else {
      ElMessage.error('获取报名数据失败')
    }
  } catch (error) {
    ElMessage.error('获取报名数据失败')
    console.error('获取报名数据错误:', error)
  } finally {
    registrationLoading.value = false
  }
}

// 处理下拉菜单命令
const handleCommand = async (command, activity) => {
  if (command === 'changeStatus') {
    await handleChangeStatus(activity)
  } else if (command === 'delete') {
    await handleDelete(activity)
  }
}

// 修改活动状态
const handleChangeStatus = async (activity) => {
  const newStatus = activity.status === 'active' ? 'pending' : 'active'
  const action = newStatus === 'active' ? '启用' : '暂停'
  
  try {
    await ElMessageBox.confirm(
      `确定要${action}活动 "${activity.title}" 吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const result = await CloudBaseAPI.changeActivityStatus(activity._id, newStatus)
    
    if (result.success) {
      ElMessage.success(`${action}成功`)
      getActivityList()
    } else {
      ElMessage.error(result.message || `${action}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`${action}失败`)
      console.error('修改活动状态错误:', error)
    }
  }
}

// 删除活动
const handleDelete = async (activity) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除活动 "${activity.title}" 吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    const result = await CloudBaseAPI.deleteActivity(activity._id)
    
    if (result.success) {
      ElMessage.success('删除成功')
      getActivityList()
    } else {
      ElMessage.error(result.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除活动错误:', error)
    }
  }
}

// 导出报名数据
const exportRegistrations = () => {
  // 这里可以实现导出功能
  ElMessage.info('导出功能开发中...')
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

// 获取状态类型（根据汉字状态返回对应的tag类型）
const getStatusType = (status) => {
  const statusMap = {
    '报名中': 'warning',
    '进行中': 'success',
    '已结束': 'info',
    '已取消': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本（直接返回数据库中的汉字状态）
const getStatusText = (status) => {
  return status || '未知'
}

// 预处理所有活动的图片URL
const processAllImageUrls = async () => {
  // 为每个活动单独处理图片URL
  for (const activity of activityList.value) {
    if (activity.bannerImage && activity.bannerImage.startsWith('cloud://')) {
      try {
        const tempUrl = await CloudBaseAPI.getTempFileURL(activity.bannerImage)
        // 使用Vue的响应式更新
        activity.bannerImage = tempUrl
      } catch (error) {
        console.error(`处理图片 ${activity.bannerImage} 失败:`, error)
      }
    }
  }
}


onMounted(() => {
  getActivityList()
})
</script>

<style scoped>
.activity-management {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}


:deep(.el-table .cell) {
  word-break: break-all;
}
</style>